package com.distribution.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.distribution.system.domain.entity.AddressSystem;
import com.distribution.system.domain.vo.CityVO;
import com.distribution.system.domain.vo.TableArea;
import com.distribution.system.mapper.AddressSystemMapper;
import com.distribution.system.service.AddressSystemService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: GodLu
 * @create: 2024-10-24 09:29
 * @description: TODO
 */
@Service
public class AddressSystemServiceImpl extends ServiceImpl<AddressSystemMapper, AddressSystem> implements AddressSystemService {
    @Override
    public String getProvinceCodeByName(String provinceName) {
        List<AddressSystem> addressSystemList = lambdaQuery().likeRight(AddressSystem::getProvinceName, provinceName).list();
        return (addressSystemList == null || addressSystemList.isEmpty()) ? null : addressSystemList.get(0).getProvinceCode();
    }

    @Override
    public String getProvinceNameByCode(String provinceCode) {
        List<AddressSystem> addressSystemList = lambdaQuery().eq(AddressSystem::getProvinceCode, provinceCode).list();
        return (addressSystemList == null || addressSystemList.isEmpty()) ? null : addressSystemList.get(0).getProvinceName();
    }

    @Override
    public String getCityCodeByName(String cityName) {
        List<AddressSystem> addressSystemList = lambdaQuery().likeRight(AddressSystem::getCityName, cityName).list();
        return (addressSystemList == null || addressSystemList.isEmpty()) ? null : addressSystemList.get(0).getCityCode();
    }

    @Override
    public String getCityNameByCode(String cityCode) {
        List<AddressSystem> addressSystemList = lambdaQuery().eq(AddressSystem::getCityCode, cityCode).list();
        return (addressSystemList == null || addressSystemList.isEmpty()) ? null : addressSystemList.get(0).getCityName();
    }

    @Override
    public String getDistrictCodeByName(String districtName) {
        List<AddressSystem> addressSystemList = lambdaQuery().likeRight(AddressSystem::getDistrictName, districtName).list();
        return (addressSystemList == null || addressSystemList.isEmpty()) ? null : addressSystemList.get(0).getDistrictCode();
    }

    @Override
    public String getDistrictNameByCode(String districtCode) {
        List<AddressSystem> addressSystemList = lambdaQuery().eq(AddressSystem::getDistrictCode, districtCode).list();
        return (addressSystemList == null || addressSystemList.isEmpty()) ? null : addressSystemList.get(0).getDistrictName();
    }

    @Override
    public JSONArray getPickerAreaMap(String productParam) {
        List<AddressSystem> addressSystemList = list();
        //Map<String,List<Map<String,List<String>>>>
        JSONArray returnJsonArray = new JSONArray();
        Map<String, List<AddressSystem>> provinceMap = addressSystemList.stream()
                .collect(Collectors.groupingBy(v -> v.getProvinceCode() + "_" + v.getProvinceName()));
        Map<String, List<AddressSystem>> provinceResult = new LinkedHashMap<>();
        provinceMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> provinceResult.put(x.getKey(), x.getValue()));
        //System.out.println(provinceResult.keySet());
        for (String provinceKey : provinceResult.keySet()) {
            String[] provinceSplit = provinceKey.split("_");
            JSONObject provinceJson = new JSONObject();
            //provinceJson.put(provinceSplit[0],provinceSplit[1]);
            JSONArray cityJsonArray = new JSONArray();

            Map<String, List<AddressSystem>> cityMap = addressSystemList.stream()
                    .filter(f -> f.getProvinceName().equals(provinceSplit[1]))
                    .collect(Collectors.groupingBy(v -> v.getCityCode() + "_" + v.getCityName()));
            Map<String, List<AddressSystem>> cityResult = new LinkedHashMap<>();
            cityMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> cityResult.put(x.getKey(), x.getValue()));
            //System.out.println(cityResult.keySet());
            for (String cityKey : cityResult.keySet()) {
                String[] citySplit = cityKey.split("_");
                JSONObject cityJson = new JSONObject();
                //cityJson.put(citySplit[0],citySplit[1]);
                JSONArray countyJsonArray = new JSONArray();

                Map<String, List<AddressSystem>> countyMap = addressSystemList.stream()
                        .filter(f -> f.getProvinceName().equals(provinceSplit[1]) && f.getCityName().equals(citySplit[1]))
                        .collect(Collectors.groupingBy(v -> v.getDistrictCode() + "_" + v.getDistrictName()));
                Map<String, List<AddressSystem>> countyResult = new LinkedHashMap<>();
                countyMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> countyResult.put(x.getKey(), x.getValue()));
                //System.out.println(countyResult.keySet());
                for (String countyKey : countyResult.keySet()) {
                    String[] countySplit = countyKey.split("_");
                    JSONObject countyJson = new JSONObject();
                    countyJson.put(countySplit[0],countySplit[1]);
                    countyJsonArray.add(countyJson);
                }
                cityJson.put(citySplit[0] + "_" + citySplit[1],countyJsonArray);
                cityJsonArray.add(cityJson);
            }
            provinceJson.put(provinceSplit[0] + "_" + provinceSplit[1],cityJsonArray);
            returnJsonArray.add(provinceJson);
            //System.out.println(returnJsonArray);
        }
        return returnJsonArray;
    }

    @Override
    public Map<String, Object> selectArea(String productParam) {
        List<AddressSystem> list = list();
        //System.out.println("list = " + list);
        Map<String, Object> objectObjectHashMap = new LinkedHashMap<>();
        HashMap<String, String> objectObjectHashMap1 = new LinkedHashMap<>();
        Map<String, List<AddressSystem>> addressSystemGroupMap = list.stream().collect(Collectors.groupingBy(v -> v.getProvinceCode()
                + "_" + v.getProvinceName()));

        Map<String, List<AddressSystem>> result1 = new LinkedHashMap<>();
        addressSystemGroupMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result1.put(x.getKey(), x.getValue()));
        result1.forEach((key,value) ->{
            String[] keyArr = key.split("_");
            String provinceCode = keyArr[0];
            String proniceName = keyArr[1];
            objectObjectHashMap1.put(provinceCode,proniceName);
        });

        objectObjectHashMap.put("provinceList",objectObjectHashMap1);

        HashMap<String, String> objectObjectHashMap2 = new LinkedHashMap<>();
        Map<String, List<AddressSystem>> ysAreaGroupMap1 = list.stream().collect(Collectors.groupingBy(v -> v.getCityCode()
                + "_" + v.getCityName()));
        Map<String, List<AddressSystem>> result2 = new LinkedHashMap<>();
        ysAreaGroupMap1.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

        result2.forEach((key,value) ->{
            String[] keyArr = key.split("_");
            String cityCode = keyArr[0];
            String cityName = keyArr[1];
            objectObjectHashMap2.put(cityCode,cityName);
        });

        objectObjectHashMap.put("cityList",objectObjectHashMap2);

        HashMap<String, String> objectObjectHashMap3 = new LinkedHashMap<>();
        Map<String, List<AddressSystem>> ysAreaGroupMap2 = list.stream().collect(Collectors.groupingBy(v -> v.getDistrictCode()
                + "_" + v.getDistrictName()));
        Map<String, List<AddressSystem>> result3 = new LinkedHashMap<>();
        ysAreaGroupMap2.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result3.put(x.getKey(), x.getValue()));
        result3.forEach((key,value) ->{
            String[] keyArr = key.split("_");
            String districtCode = keyArr[0];
            String districtName = keyArr[1];
            objectObjectHashMap3.put(districtCode,districtName);
        });
        objectObjectHashMap.put("countyList",objectObjectHashMap3);
        //System.out.println("objectObjectHashMap = " + objectObjectHashMap);
        return objectObjectHashMap;
    }

    @Override
    public List<TableArea> getSystemAddressList() {
        List<AddressSystem> list = lambdaQuery().orderByAsc(AddressSystem::getDistrictCode).list();
        Map<String, List<AddressSystem>> collect = list.stream().collect(Collectors.groupingBy(AddressSystem::getProvinceCode));
        List<TableArea> tableAreas = new ArrayList<>();
        collect.forEach((key,value)->{
            TableArea tableArea = new TableArea();
            tableArea.setCode(key);
            tableArea.setName(value.get(0).getProvinceName());
            Map<String, List<AddressSystem>> countyMap = value.stream().collect(Collectors.groupingBy(AddressSystem::getCityCode));
            Map<String, List<AddressSystem>> countyResult = new LinkedHashMap<>();
            countyMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> countyResult.put(x.getKey(), x.getValue()));
            List<TableArea> tableAreasCity = new ArrayList<>();
            countyResult.forEach((key1,value1)->{
                TableArea tableAreaCity = new TableArea();
                tableAreaCity.setCode(key1);
                tableAreaCity.setName(value1.get(0).getCityName());
                tableAreasCity.add(tableAreaCity);

            });
            tableArea.setChildren(tableAreasCity);
            tableAreas.add(tableArea);
        });
        return tableAreas.stream().sorted(Comparator.comparing(TableArea::getCode)).collect(Collectors.toList());
    }

    @Override
    public Map<String, String> getProvinceMap(String productCode) {
        List<AddressSystem> addressSystemList = list();
        Map<String,String> map = new HashMap<>();
        for (AddressSystem addressSystem : addressSystemList) {
            map.put(addressSystem.getProvinceCode(),addressSystem.getProvinceName());
        }
        List<String> sortKey = map.keySet().stream().sorted().collect(Collectors.toList());
        Map<String,String> sortMap = new LinkedHashMap<>();
        for (String key : sortKey) {
            sortMap.put(key,map.get(key));
        }
        return sortMap;
    }

    @Override
    public List<CityVO> getCityList(String productCode) {
        List<CityVO> cityVOList = new ArrayList<>();
        List<AddressSystem> ysAreaTotalList = list();
        Map<String,String> map = new HashMap<>();
        for (AddressSystem addressSystem : ysAreaTotalList) {
            map.put(addressSystem.getCityCode(),addressSystem.getCityName());
        }
        List<String> sortKey = map.keySet().stream().sorted().collect(Collectors.toList());
        Map<String,String> sortMap = new LinkedHashMap<>();
        for (String key : sortKey) {
            sortMap.put(key,map.get(key));
        }
        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            CityVO cityVO = new CityVO();
            cityVO.setCityCode(entry.getKey());
            cityVO.setCityName(entry.getValue());
            for (AddressSystem addressSystem : ysAreaTotalList) {
                if (entry.getKey().equals(addressSystem.getCityCode())){
                    cityVO.setProvinceCode(addressSystem.getProvinceCode());
                    break;
                }
            }
            cityVOList.add(cityVO);
        }
        return cityVOList;
    }
}
